import { Col, Form, Input, message, Modal, Radio, Row } from 'antd';

import parameterService from '@/api/services/stars/parameterService';

import { ParameterType } from './type';

import { ModalProps } from '#/entity';

export default function ParameterModal({
  title,
  show,
  onOk,
  onCancel,
  formValue,
}: ModalProps<ParameterType>) {
  const [form] = Form.useForm();

  const onFinish = (values) => {
    if (formValue.id) {
      parameterService.updateParameter(formValue.id, values).then((res) => {
        if (res > 0) {
          message.success('修改成功');
          onOk();
        }
      });
    } else {
      parameterService.createParameter(values).then((res) => {
        if (res > 0) {
          message.success('新增成功');
          onOk();
        }
      });
    }
  };

  // __________________________________________________________________
  const modalRender = (dom: React.ReactNode) => (
    <Form
      onFinish={onFinish}
      initialValues={formValue}
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      clearOnDestroy
      layout="horizontal"
      // layout="vertical"
    >
      {dom}
    </Form>
  );
  const required = true;
  return (
    <Modal
      width={600}
      destroyOnHidden
      title={title}
      open={show}
      onCancel={onCancel}
      modalRender={modalRender}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
    >
      <Row gutter={24}>
        <Col span={24}>
          <Form.Item name="name" label="参数名" rules={[{ required }]}>
            <Input />
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item
            name="key"
            label="参数键"
            rules={[{ required }]}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
          >
            <Input disabled={formValue.system} />
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item name="value" label="参数值" rules={[{ required }]}>
            <Input />
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="系统内置" name="system" rules={[{ required }]}>
            <Radio.Group
              block
              buttonStyle="solid"
              optionType="button"
              options={[
                { value: true, label: '是' },
                { value: false, label: '否' },
              ]}
            />
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item
            label="备注"
            name="remark"
            rules={[
              {
                max: 256,
                message: `内容不能超过 256 个字符`,
              },
            ]}
          >
            <Input.TextArea showCount maxLength={256} />
          </Form.Item>
        </Col>
      </Row>
    </Modal>
  );
}
